package org.nanhill.moo.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nanhill.commons.pattern.domain.DomainAlreadyExistException;
import org.nanhill.moo.domain.User;
import org.nanhill.moo.service.UserService;
import org.nanhill.moo.web.UserSession;
import org.nanhill.moo.web.form.RegisterUserForm;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

/**
 * Controller for user register.
 * 
 * @author alin
 */
public class RegisterUserController extends NamedFormController {
	private static final String FORM_NAME = "registerUserForm";

	private UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public RegisterUserController() {
		setCommandClass(RegisterUserForm.class);
		setCommandName(FORM_NAME);
		setSubmitType(FORM_NAME);
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		RegisterUserForm form = (RegisterUserForm) command;
		User register = form.createUser();
		try {
			this.userService.open(register);
		} catch (DomainAlreadyExistException e) {
			errors.rejectValue("email", "errors.alreadyexist", null, null);
			return this.showForm(request, response, errors);
		}
		UserSession.initUserSession(register, request);
		return new ModelAndView(this.getSuccessView());
	}

}